package com.github.sbb.sherry.primitives.rules.jexl;

import com.github.sbb.sherry.primitives.api.Condition;
import com.github.sbb.sherry.primitives.api.Facts;
import java.util.Objects;
import org.apache.commons.jexl3.JexlEngine;
import org.apache.commons.jexl3.JexlScript;
import org.apache.commons.jexl3.MapContext;


public class JexlCondition implements Condition {

  private final JexlScript compiledScript;

  public JexlCondition(String expression) {
    Objects.requireNonNull(expression, "expression cannot be null");
    this.compiledScript = JexlRule.DEFAULT_JEXL.createScript(expression);
  }

  public JexlCondition(String expression, JexlEngine jexl) {
    Objects.requireNonNull(expression, "expression cannot be null");
    Objects.requireNonNull(jexl, "jexl cannot be null");
    this.compiledScript = jexl.createScript(expression);
  }

  @Override
  public boolean evaluate(Facts facts) {
    Objects.requireNonNull(facts, "facts cannot be null");
    MapContext ctx = new MapContext(null);
    return (Boolean) compiledScript.execute(ctx);
  }
}
